$(function () {
    // Funciones twitter
    $("#tweets").hide();
    // Obtiene la lista de tweets de un ususario
    $(".list-twitter a").click(function() {
      var nombre = $(this).text();
      var usuario = $(this).children().val();
      $("#up, #down").slideUp("fast");
      $("ul.tweetList").remove();
      $("#tweets p").append("Ultimos tweets de: <span style='font-weight: bold'>" + nombre + "<a href='https://twitter.com/intent/user?original_referer=https%3A%2F%2Ftwitter.com%2Fabout%2Fresources%2Ffollowbutton&region=following&screen_name=" + usuario + "&source=followbutton&variant=1.1' target='_blank' ><img class='button' src='images/followbutton.png'/></a>" +"</span>");
      $("#tweets").tweetable({
          username: usuario,
          time: true,
          limit: 10,
          replies: true,
          position: 'append'
      });
      $("#tweets").slideDown("slow");
    });
    
    // Codigo para la carga de los feeds en las distintas paginas
    // URL de la pagina
    var url = $(location).attr("href");
    var base = $(location).attr("host");
    var ruta = "";
    
    //Si estamos probando en local
    if (base == "localhost:8080")
        ruta = $(location).attr("protocol") + "//" + base + "/NoticiasDeportes/";
    else
        ruta = $(location).attr("protocol") + "//" + base + "/";
    
    // Nombre de las paginas que muestran noticias
    var index = ruta + "index.html";
    var futbol = ruta + "futbol.html";
    var baloncesto = ruta + "baloncesto.html";
    var motor = ruta + "motor.html"; 
    
    var channel = "";
    if (url.endsWith(index) || url == ruta) channel = "http://www.as.com/rss.html";
    else if (url.endsWith(futbol)) channel = "http://www.as.com/rss/feed.html?feedId=61";
    else if (url.endsWith(baloncesto)) channel = "http://www.as.com/rss/feed.html?feedId=62";
    else if (url.endsWith(motor)) channel = "http://www.as.com/rss/feed.html?feedId=63";
    
    if (channel != "") {
        $.jGFeed(channel,
            function(feeds){
            // Check for errors
            if(!feeds){
              // there was an error
              return false;
            }
            // do whatever you want with feeds here
            for(var i=0; i<feeds.entries.length; i++){
              var entry = feeds.entries[i];
              // Entry title
              var noticia = "<div class='" + (i % 2 == 0 ? "par" : "impar") +"'><h3>" + entry.title + "</h3>";
              noticia += "<p class='author'>" + entry.author + " - " + entry.publishedDate + "</p><p>" + entry.content + "</p>";
              noticia += "<p><a href='" + entry.link + "' target='_blank'>Ver noticia</a></p></div>";
              $("#content").append(noticia);

            }
        }, 10);
    }
    
    // Funcines para los videos de youtube
    $(".input-button input").click(function(){
        if($(".input-box input").val()== ""){
          $("#main-video").empty();
          return false;
        }
        $(".loading").show();

        var input_search = encodeURIComponent($(".input-box input").val());
        var start_index = Math.floor(Math.random()*5) ;
        if (start_index == 0) start_index=1;

        var url_video = "http://gdata.youtube.com/feeds/api/videos?v=2&max-results=5"
        url_video += "&q="+input_search+"&format=5&start-index="+start_index+"&alt=jsonc";

        $.ajax({
          type:"GET",
          url:url_video,
          dataType:"jsonp",
          success:function(json){
            $("#main-video").empty().hide();
            if(json.data.items){
              var yb_video_frame = "";
              var yb_gallery_image = "";
              var title_video = "";

              $.each(json.data.items,function(i,data){
                var yb_video_id = data.id;
                var yb_video_title = data.title;
                var yb_video_thumb = data.thumbnail.sqDefault

                if (i==0) {
                  title_video = yb_video_title;
                  yb_video_frame += loadVideo(yb_video_id);
                }else{
                  yb_gallery_image += "<li class='video'><a class='view-video'><img src='"+yb_video_thumb+"' alt='"+yb_video_title+"' title='"+yb_video_title+"'/></a><input type='hidden' value='"+yb_video_id+"'/></li>";
                }

              })

              var main_video ="<div class='title-video'>"+title_video+"</div>";
              main_video +="<div id='video-wrapper'>"+yb_video_frame+"</div>";
              main_video +="<div class='related-videos'>Videos relacionados</div>";
              main_video +="<div class='gallery'><ul class='gallery-video'>"+yb_gallery_image+"</ul></div>";

              $(".loading").hide();
              $("#main-video").append(main_video).show();

            }
          }
        })

      });

      $(".view-video").live("click",function(){
        var id_video = $(this).parent().find("input").val();
        var title_video = $(this).find("img").attr("title");
        $("#video-wrapper").empty().append(loadVideo(id_video));
        //$("#video-wrapper").parent().find(".title_video").text(title_video);
        $(".title-video").html($(this).children().attr("title"));
      });

      $(".input-box input").focus(function() {
         $(this).val("");
      });

      $(".input-box input").blur(function() {
          if ($(this).val() == "")
            $(this).val("Buscar en Youtube ..."); 
      });
      
      // jQuery para calendarios
      $(".listLink a").click(function(event){
        event.preventDefault();
        var url = $(this).attr("href");
        var iframe = "<iframe class='ciframe' src='" + url + "' width='600' height='375' scrolling='no' frameborder='0'></iframe>";
        $("#myiframe").html(iframe);
      });

});

// Obtiene la cadena del iframe del video
function loadVideo(id_video){
  var video_frame  = "<iframe width='640' height='385' ";
  video_frame += "src='http://www.youtube.com/v/"+id_video+"&version=3&autoplay=0'";
  video_frame += " frameborder='0' type='text/html'></iframe>";
  return video_frame;
}

// Comprueba si una cadena termina con la subcadena str
String.prototype.endsWith = function(str) {
    return (this.match(str+"$")==str)
}

//define the tweetable plugin
$.fn.tweetable = function (options) {
    //specify the plugins defauls
    var defaults = {
        limit: 5, 						//number of tweets to show
        username: options[0], 	//@username tweets to display
        time: true, 					//display date
        replies: false,				//filter out @replys
        position: 'append'			//append position
    };
    //overwrite the defaults
    var options = $.extend(defaults, options);
            //loop through each instance
    return this.each(function (options) {
                    //assign our initial vars
        var act = $(this);
        var $tweetList;
        var tweetMonth = '';
        var shortMonths = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
        var api = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=";
        var count = "&count=";

        //do a JSON request to twitters API
        $.getJSON(api + defaults.username + count + defaults.limit + "&callback=?", act, function (data) {
                            //loop through twitters response
            $.each(data, function (i, item) {
                                    //check for the first loop
                if (i == 0) {
                    //create an unordered list to store tweets in
                    $tweetList = $('<ul class="tweetList">')[defaults.position.toLowerCase() + 'To'](act);
                }
                //handle @reply filtering if required
                if (defaults.replies === false) {
                    if (item.in_reply_to_status_id === null) {
                        $tweetList.append('<li class="tweet_content_' + i + '"><p class="tweet_link_' + i + '">' + item.text.replace(/#(.*?)(\s|$)/g, '<span class="hash">#$1 </span>').replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, '<a href="$&">$&</a> ').replace(/@(.*?)(\s|\(|\)|$)/g, '<a href="http://twitter.com/$1">@$1 </a>$2')+'</p></li>');
                    }
                } else {
                    $tweetList.append('<li class="tweet_content_' + i + '"><p class="tweet_link_' + i + '">' + item.text.replace(/#(.*?)(\s|$)/g, '<span class="hash">#$1 </span>').replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, '<a href="$&">$&</a> ').replace(/@(.*?)(\s|\(|\)|$)/g, '<a href="http://twitter.com/$1">@$1 </a>$2') + '</p></li>');
                }
                //display the tiem of tweet if required
                if (defaults.time == true) {
                    for(var iterate=0; iterate<=12; iterate++) {
                            if(shortMonths[iterate] == item.created_at.substr(4, 3)) {
                                                            tweetMonth = iterate + 1;
                                                            if(tweetMonth < 10) {
                                                                    tweetMonth = '0' + tweetMonth;
                                                            }
                                    } 	
                    }
                    $('.tweet_link_' + i).append('<small> ' + item.created_at.substr(8, 2) + '/' + tweetMonth + '/' + item.created_at.substr(26,4) + ' ' + item.created_at.substr(11,8) + '</small>');
                }
            });
            //close the unordered list
           });
    });
}